package com.ruoyi.web.controller.distribution;

import cn.distribution.groupManager.entity.dao.GroupManagerDAO;
import cn.distribution.groupManager.entity.vo.GroupManagerVO;
import cn.distribution.groupManager.service.GroupManagerService;
import cn.distribution.messagesManager.entity.dao.MessagesManagerDAO;
import cn.distribution.messagesManager.entity.vo.MessagesManagerVO;
import cn.distribution.messagesManager.service.MessagesManagerService;
import cn.distribution.personManager.entity.dao.PersonManagerDAO;
import cn.distribution.personManager.entity.vo.personTemplateVO;
import cn.distribution.personManager.service.PersonManagerService;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.*;

/**
 * @author zhengminjie
 */
@RestController
@RequestMapping("/distribution/groupManager")
public class GroupManagerController extends BaseController {
    protected final Logger logger = LoggerFactory.getLogger(GroupManagerController.class);

    @Autowired
    private GroupManagerService groupManagerService;

    @Autowired
    private PersonManagerService personManagerService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private MessagesManagerService messagesManagerService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private TokenService tokenService;

    @GetMapping("/search")
    public TableDataInfo searchGroupList(Long groupNum, String groupName) {
        List<GroupManagerVO> groupManagerVOList;
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        startPage();
        groupManagerVOList = this.groupManagerService.getGroup(userId,groupNum,groupName);
        logger.info(groupManagerVOList.toString());
        return getDataTable(groupManagerVOList);
    }

    @GetMapping("/searchAll")
    public TableDataInfo searchAllGroupList(Long groupNum, String groupName) {
        startPage();
        List<GroupManagerDAO> groupManagerDAOList;
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        groupManagerDAOList = this.groupManagerService.getGroupAll(userId,groupNum,groupName);
        logger.info(groupManagerDAOList.toString());
        return getDataTable(groupManagerDAOList);
    }

    @PostMapping("/create")
    public AjaxResult createGroup(@RequestBody GroupManagerDAO groupManagerDAO){
        GroupManagerDAO groupManagerDAO1 = new GroupManagerDAO();
        Date date = new Date();
        long groupNum = date.getTime()%Long.parseLong("1620000000000");
        groupManagerDAO1.setGroupNum(groupNum);
        groupManagerDAO1.setGroupName(groupManagerDAO.getGroupName());
        groupManagerDAO1.setGroupPermission(groupManagerDAO.getGroupPermission());
        groupManagerDAO1.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        groupManagerDAO1.setUserName(SecurityUtils.getLoginUser().getUser().getUserName());
        this.groupManagerService.save(groupManagerDAO1);
        PersonManagerDAO personManagerDAO = new PersonManagerDAO();
        personManagerDAO.setGroupId(this.groupManagerService.getIdByNum(groupManagerDAO1.getGroupNum()));
        personManagerDAO.setUserId(groupManagerDAO1.getUserId());
        personManagerDAO.setGroupNum(groupNum);
        personManagerDAO.setUserIdentity("创建者");
        personManagerDAO.setDataDistribution(true);
        this.personManagerService.save(personManagerDAO);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        Long roleIds[]={Long.parseLong("100")};
        sysUser.setRoleIds(roleIds);
        this.sysUserService.updateUser(sysUser);
        return AjaxResult.success("创建群组成功");
    }

    @PostMapping("/add")
    public AjaxResult addGroup(@RequestBody MessagesManagerVO messagesManagerVO){
        List<Long> groupNum = messagesManagerVO.getGroupNum();
        long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        PersonManagerDAO personManagerDAO = new PersonManagerDAO();
        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
        for(Long num:groupNum){
            long groupId = this.groupManagerService.getIdByNum(num);
            GroupManagerDAO groupManagerDAO = this.groupManagerService.getById(groupId);
            if(!groupManagerDAO.getGroupPermission()){
                personManagerDAO.setGroupId(groupId);
                personManagerDAO.setGroupNum(num);
                personManagerDAO.setUserId(userId);
                personManagerDAO.setUserIdentity("普通人");
                personManagerDAO.setDataDistribution(false);
                this.personManagerService.save(personManagerDAO);
            }else {
                List<Long> allUserId = this.personManagerService.getUserIdByNum(num, "普通人");
                for (Long Id : allUserId) {
                    messagesManagerDAO.setUserName(iSysUserService.selectUserById(Id).getUserName());
                    messagesManagerDAO.setMessageType(messagesManagerVO.getMessageType());
                    messagesManagerDAO.setMessageContent(messagesManagerVO.getMessageContent());
                    String content = num.toString() + "," + userId + "," + messagesManagerVO.getContent();
                    messagesManagerDAO.setContent(content);
                    messagesManagerDAO.setState(false);
                    messagesManagerDAO.setCreateTime(new Date());
                    this.messagesManagerService.save(messagesManagerDAO);
                }
            }
        }
        return AjaxResult.success("添加群组成功");
    }
    @PostMapping("/delete")
    public AjaxResult deleteGroup(@RequestBody  List<Long> groupNum){
        long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
        for(Long num:groupNum){
            Long id = this.groupManagerService.getIdByNum(num);
            String identity = this.personManagerService.getIdentityByNum(num,userId);
            if(Objects.equals(identity, "创建者")){
                // 给这些成员发一条消息
                List<Long> allUserId = this.personManagerService.getUserIdByNum(num,"创建者");
                for(Long Id:allUserId){
                    messagesManagerDAO.setUserName(iSysUserService.selectUserById(Id).getUserName());
                    messagesManagerDAO.setMessageType(Long.parseLong("3"));
                    messagesManagerDAO.setMessageContent("你有一条被删消息");
                    messagesManagerDAO.setContent("很可惜你与"+this.groupManagerService.getNameByNum(num)+"群无缘");
                    messagesManagerDAO.setState(false);
                    messagesManagerDAO.setCreateTime(new Date());
                    this.messagesManagerService.save(messagesManagerDAO);
                }
                // 删除这个群
                this.groupManagerService.removeById(id);
                // 删除这个群有关的成员
                this.personManagerService.deleteAllGroup(num);
            }
            else{
                // 退出这个群
                this.personManagerService.deleteGroup(num,userId);
            }
        }
        return AjaxResult.success("删除群组成功");
    }

    @PostMapping("/band")
    public AjaxResult bandIdentity(@RequestBody  PersonManagerDAO personManagerDAO){
        // 查找用户身份编号有没有相同的
        Long ifSome = this.personManagerService.getIfSame(personManagerDAO);
        if(ifSome == 0){
            // 更新成员列表
            long userId = SecurityUtils.getLoginUser().getUser().getUserId();
            personManagerDAO.setUserId(userId);
            this.personManagerService.updateNumber(personManagerDAO);
            return AjaxResult.success("绑定身份信息成功");
        }
        return AjaxResult.success("绑定身份信息失败");
    }
}
